package com.smp.support.restTemplate;

import com.alibaba.fastjson.JSONObject;
import lombok.extern.slf4j.Slf4j;
import org.springframework.http.*;
import org.springframework.stereotype.Component;
import org.springframework.util.CollectionUtils;
import org.springframework.web.client.RestTemplate;

import javax.annotation.Resource;
import java.util.Iterator;
import java.util.Map;

/**
 * @author: fangxiaoyu
 * @date: 2021/6/15
 * @description:
 **/
@Slf4j
@Component
public class RestClient {

    @Resource
    private RestTemplate restTemplate;

    public ResponseEntity execute(RestRequest request) {
        String url;
        HttpHeaders headers = new HttpHeaders();
        headers.setContentType(MediaType.APPLICATION_JSON);
        if (request.getHttpHeaders().size() > 0) {
            request.getHttpHeaders().forEach((key, val) -> {
                headers.add(key, val);
            });
        }
        HttpEntity<Object> entity = new HttpEntity<>(headers);
        if (HttpMethod.POST == request.getMethod()) {
            JSONObject json = new JSONObject();
            if (!CollectionUtils.isEmpty(request.getParams())) {
                Iterator<Map.Entry<String, Object>> entries = request.getParams().entrySet().iterator();
                while (entries.hasNext()) {
                    Map.Entry<String, Object> entry = entries.next();
                    json.put(entry.getKey(), entry.getValue());
                }
            }
            entity = new HttpEntity<>(json, headers);
            url = request.getUrl();
        } else {
            StringBuffer params = new StringBuffer(request.getUrl() + "?");
            if (!CollectionUtils.isEmpty(request.getParams())) {
                Iterator<Map.Entry<String, Object>> entries = request.getParams().entrySet().iterator();
                while (entries.hasNext()) {
                    Map.Entry<String, Object> entry = entries.next();
                    params.append(entry.getKey()).append("=").append(entry.getValue()).append("&");
                }
            }
            url = params.toString();
        }
        Class source = request.getClassz() == null ? String.class : request.getClassz();
        return restTemplate.exchange(url, request.getMethod(), entity, source);
    }

}
